package com.lazybones.base.engineer.common.conf.cors;

import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Collections;

@Configuration
public class ApplicationCorsConfigure implements WebMvcConfigurer {

    /**
     * @param registry
     * 解决跨域，权限很大，允许所有
     */
    @Override
    public void addCorsMappings(@NotNull CorsRegistry registry){
        registry.addMapping("/**")
                .allowedHeaders("*").allowedOrigins("*").allowedMethods("*")
                .allowCredentials(false);
    }
    @Bean
    public CorsFilter corsFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        // 设置允许凭据
        config.setAllowCredentials(true);
        config.setAllowedHeaders(Collections.singletonList("*"));
        config.setAllowedOrigins(Collections.singletonList("*"));
        config.setAllowedMethods(Collections.singletonList("*"));
        config.setMaxAge(12000L);
        source.registerCorsConfiguration("/**",config);
        return  new CorsFilter(source);
    }
}
